<template>
  <div class="the-list">

    <div class="panel-table">
      <div class="table-head">
        <div>
         登录日志
        </div>
      </div>
      <el-table :data="tableData.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>
        <el-table-column prop="createdAt" label="时间" />
        <el-table-column prop="clientIp" label="IP" />
        <el-table-column prop="ipCity" label="地区" />
        <el-table-column prop="device" label="设备" />
        <el-table-column prop="osVersion" label="系统版本" />
        <el-table-column prop="appVersion" label="应用版本" />
      </el-table>

      <div class="table-pagination">
        <pagination :total="tableData.total" v-model:page="tableData.query.page" v-model:limit="tableData.query.pageSize" @pagination="tableFn.getTableData" />
      </div>

    </div>

  </div>
</template>

<script>
import { reactive, ref, watchEffect } from "vue";
import Pagination from "@/components/Pagination";
import { getCustomerLoginList } from "@/api/videouser.js";
import { onBeforeRouteUpdate, useRouter } from 'vue-router';

export default {
  components:{
    Pagination,
  },
  setup() {
    const router = useRouter();
    const params = ref({});
    const query = ref({});
    watchEffect(()=>{
      params.value = router.currentRoute.value.params;
    })
    watchEffect(()=>{
      query.value = router.currentRoute.value.query;
    })
    // 默认数据备份，以便重置或恢复
    const { $data: tableData, $fn: tableFn } = tableModule(params);

    function init(){
      tableFn.getTableData();
    }
    init()

    // 从相同路由进入（params不同，query.view相同），如/a/b/1?view=1 => /a/b/2?view=1
    onBeforeRouteUpdate((to, from, next) => {
      if(to.params.id !== from.params.id && to.query.view === from.query.view){
        params.value.id = to.params.id;
        query.value = to.query;
        init();
      }
      next();
    });
    
    return {
      tableData,
      tableFn,
    };
  },
};

// 表格功能模块，包括搜索，分页等
function tableModule(params) {
  const backup = {
    query: {
      customerId: params.value.id,
      pageSize: 10,
      page: 1,
    },
  };

  const $data = reactive({
    query: { ...backup.query },
    list: [],
    total: 0,
  });
  const $fn = {
    getTableData() {
      let id = params.value.id;
      getCustomerLoginList({...$data.query,customerId:id}).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    onResetQuery() {
      $data.query = { ...backup.query };
      $fn.getTableData();
    },
    onSubmit() {
      $fn.getTableData();
    },
    pageChange(value) {
      $data.query.page = value;
      $fn.getTableData();
    },
    pageSizeChange(value) {
      $data.query.pageSize = value;
      $fn.getTableData();
    },
  };

  return {
    $data,
    $fn,
  };
}
</script>

<style scoped lang="scss">
@import "@/styles/tablePage.scss";
</style>